import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

import '../Robot.dart';
import '../details.dart';
import '../pojo.dart';

class CustomerDetailsProvider extends ChangeNotifier {
  CustomerDetailsProvider();

  // Customer information fields
  String _customerName = "";
  String _phoneNumber = "";
  final String _customerType = "";
  int _renderCount = 0;
  double _totalAmount = 0.0;

  // Getter methods for each property
  String get customerName => _customerName;
  String get phoneNumber => _phoneNumber;
  String get customerType => _customerType;
  int get renderCount => _renderCount;
  double get totalAmount => _totalAmount;

  //  客户渲染详情
  List<Task> _list2 = [];
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  List<Item147> dataList2 = [];
//界面只需要这个
  List<Item147> get list3 => dataList2;

  ///客户渲染详情
  Future<void> getCustomerDetails(String accessToken,String userId,String companyId,String  name, String  phone,double  total) async {
    print("客户渲染详情 start");
    _isLoading = true;
    _totalAmount = total;
    // 创建 Condition3 对象
    Condition7 condition = Condition7(customerName: name, customerPhone: phone);

    // 创建 FetchDataRequest9 对象
    FetchDataRequest9<Condition7> request = FetchDataRequest9<Condition7>(
      condition: condition,
    );

    var url = Uri.https(host, 'userOrderCustomer/detail/page');
    final uri = url.replace(
      queryParameters: {
        "access_token": accessToken,
        "userId": userId,
        "companyId": companyId,
      },
    );

    final a = jsonEncode(request.toJson((condition) => condition.toJson()));
    final response = await http.post(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
      body: a,
    );
    print("客户渲染详情   1 ");
    print("客户渲染详情 access_token:  "+accessToken);
    print("客户渲染详情 userId:  "+userId);
    print("客户渲染详情 companyId:  "+companyId);

    if (response.statusCode == 200) {
      print("客户渲染详情： response：${response.body}");
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      _isLoading = false;
      // print("getCompanyProduct end");
      var a = ApiResponse<Data963>.fromJson(
        jsonResponse,
        (data) => Data963.fromJson(data),
      );
      _list2 = a.data!.list;

      _customerName = name;
      _phoneNumber= phone;
      _renderCount=_list2.length;

      print("客户渲染详情 2");

      Map<String, List<Task>> groupedData = {};

      // 创建一个日期格式化器
      final formatter = DateFormat("yyyy-M-d HH:mm:ss");
      for (var task in _list2) {
        if (task.endTime.isNotEmpty) {
          // 将字符串解析为 DateTime 对象
          DateTime date = formatter.parse(task.endTime);
          // 创建键值字符串 "2023年7月"
          String key = "${date.year}年${date.month}月";
          // 将项目添加到相应的分组中
          groupedData.putIfAbsent(key, () => []).add(task);
        }
      }

// 打印分组结果
      groupedData.forEach((key, value) {
        print('分组结果 : $key: ${value.length} 项');
      });

      dataList2.clear();

      // 遍历分组数据并填充 dataList2
      groupedData.forEach((key, items) {
        print("分组: $key");

        // 添加分组标题
        dataList2.add(Item147(
          position: -1,
          id: "0",
          isTitle: true,
          success: true,
          name: key,
          date: "",
        ));


        // 添加每个任务项
        for (var i = 0; i < items.length; i++) {
          int position;

          if (i == 0) {
            position = 0; // First item
          } else if (i == items.length - 1) {
            position = 2; // Last item
          } else {
            position = 1; // Middle items
          }
          if( items.length== 1){
            position = 3;
          }
          dataList2.add(Item147(
            position: position,
            id: items[i].id,
            url: items[i].url,
            isTitle: false,
            success: items[i].status == 15,
            name: items[i].designName,
            date: items[i].endTime,
            renderTotalAmount: items[i].renderTotalAmount,
            quoteTotalAmount: items[i].quoteTotalAmount,
            housePlanName: items[i].housePlanName,
          ));
          print("  - ${items[i].designName} (ID: ${items[i].id}, Position: $position)");
        }
      });

      for (var value in dataList2) {
        print('最终结果 : ${value.toJson()}');
      }
      notifyListeners();
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }
}

const fetchSize = 24;
